<?php
namespace app\api\controller\account;

use app\api\controller\Base;
use app\api\controller\Pub;
use app\common\model\account\AccountOutWarehouse;
use app\common\model\account\AccountInWarehouse;
use app\common\model\account\AccountSelfUse;
use app\common\model\account\AccountEntrustUse;
use app\common\model\account\AccountLink;
use app\common\model\company\Company;
use think\facade\Request;
use app\common\model\user\User AS UserModel;
//产废单位 产生台账
class Aoutwarehouse extends Base
{
    public function initialize()
    {
        parent::initialize();
        self::is_login();
        // Rolepower::powerguard(801001);
    }

    //获取基础信息
    //字段信息：产生部门经办人 去向 运送经办人 贮存经办人 产废设施列表 贮存设施编码 贮存设施类型
    //数据信息：最近的危废代码 、 上一次台账信息


    // 创建产生台账
    public function create()
    {
        $data = input('post.');
        //是否勾选生成入库订单
        $endflag = 0;
        //组合台账 如果结束标志不为空 创建
        if(!empty($data['has_link'])){
            if($data['has_link'] =='SelfUse'){
                $new['Golng'] = '自利用';
                $endflag = 1;
            }else if($data['has_link'] =='EntrustUse'){
                $new['Golng'] = '委外利用';
                $endflag = 1;
            }
        }
        $CreatUserId = Pub::userid();
        if(empty($data['list'])){
        	return myerr('没有找到台账列表');
        }
        $data['list'] = json_array($data['list'],true);
        $nlist = [];//新建列表
        $filelist = ['GoodId','GoodName','AccountTime','UpNote','Quantity','BoxType','BoxCount','BoxBatchCode','OrderListId','OutWarehouseUserId','TransportUserName','InWarehouseBatchCode'];//产废字段
        //自利用字段
        $selfusefile = ["EquipmentName","Type","EquipmentCode","UseType","UseEndTime","UseUserName","UseUserId","SourceBatchCode"];
        //委外利用字段
        $entrustusefile = ['AcceptingUnitType','Type','AcceptingUnitName','AcceptingUnitCode','ExemptionUnitName','AbroadUnitName','AbroadUnitCode','SourceBatchCode'];
        $company =  Company::user_getinfo();//获取产废单位企业信息
        if(empty($company)){
        	return myerr('缺少企业信息');
        }
        $company_id = $company->CompanyId;
        foreach ($data['list'] as $key => $value) {
        	$new['CompanyId'] = $company['CompanyId']; 
        	//组合产废台账信息
			$new['BatchCode'] = AccountOutWarehouse::getBatchCode($company_id);
			$new['EndFlag'] = $endflag;
			$new['CreatUserId'] = $CreatUserId;
			$new['UpdateTime'] = date('Y-m-d H:i:s',time());
			$new['Unit'] = '公斤';
			// $new['BoxBatchCode'] = AccountCreate::getBoxBatchCode($company_id);
			foreach ($filelist as $fk => $fv) {
				$new[$fv] = empty($value[$fv])?'':trim($value[$fv]);
			}
			//创建产废台账
			$new['OutWarehouseId'] = AccountOutWarehouse::createAccount($new);
			//组合台账 如果结束标志不为空 创建
			if(!empty($endflag)){
                if($data['has_link'] =='SelfUse'){
                    //自利用字段
                    foreach ($selfusefile as $fk => $fv) {
                        $new[$fv] = empty($value[$fv])?'':trim($value[$fv]);
                    }
                    $new['SourceBatchCode'] = $new['BatchCode'];
                    $new['BatchCode'] = AccountSelfUse::getBatchCode($company_id,strtotime($value['AccountTime']),$value['Type']);
                    $new['SelfUseId'] = AccountSelfUse::createAccount($new);
                    AccountLink::createlink($new);
                }else if($data['has_link'] =='EntrustUse'){
                    //委外处置字段
                    foreach ($entrustusefile as $fk => $fv) {
                        $new[$fv] = empty($value[$fv])?'':trim($value[$fv]);
                    }
                    $new['SourceBatchCode'] = $new['BatchCode'];
                    $new['BatchCode'] = AccountEntrustUse::getBatchCode($company_id,strtotime($value['AccountTime']),$value['Type']);
                    $new['EntrustUseId'] = AccountEntrustUse::createAccount($new);
                    AccountLink::createlink($new);
                }
			}
             //关联产废台账
            if(!empty($value['InWarehouseId'])){
                $sb = AccountInWarehouse::get($value['InWarehouseId']);
                if(empty($sb)){
                    return moerr('没找到此入库台账');
                }
                $new['InWarehouseId'] = $value['InWarehouseId'];
                AccountLink::createlink($new);
                $sb->EndFlag = 1;
                $sb->save();
            }
        }
        return myok('创建成功');
    }

     /**
     * 获取基础信息
     * @return [type] [description]
     */
    public function getcreateinfo()
    {
        $data = input('get.');
        $company =  Company::user_getinfo();//获取产废单位企业信息
        if(empty($company)){
            return myerr('缺少企业信息');
        }
        $company_id = $company->CompanyId;
        $data = AccountOutWarehouse::where('CompanyId',$company_id)->order('Id desc')->limit(10)->hidden(['OperationLog','goodinfo.OperationLog','goodinfo.TotalWeight'])->with('goodinfo,link,link.linkselfuse,link.linkentrustuse')->select();
        $ls = [];
        if(!empty($data)){
            $ls = AccountOutWarehouse::where('CompanyId',$company_id)->where('AccountTime',$data[0]['AccountTime'])->hidden(['OperationLog','goodinfo.OperationLog','goodinfo.TotalWeight'])->with('goodinfo,link,link.linkselfuse,link.linkentrustuse')->select();
        }
        $indata = AccountInWarehouse::where('CompanyId',$company_id)->where('EndFlag','<>',1)->order('Id desc')->limit(10)->with('goodinfo')->hidden(['OperationLog','goodinfo.OperationLog','goodinfo.TotalWeight'])->select();
        return myok(['list'=>$data,'last'=>$ls,'inwarehouse'=>$indata]);
    }
    /**
     * 修改/完善企业信息
     * 产废人信息也再次完善
     * @return [type] [description]
     */
    public function reinfo()
    {
        $data    = input('post.');
        $company = Coll::user_getinfo();
        //为空则给企业返回修改信息
        if (empty($data)) {
            return myok($company);
        }
        if (empty($company)) {
            //创建一个企业信息
            $result = $this->validate($data, 'app\common\validate\Collection');
            if (true !== $result) {
                return myerr($result);
            }
            $company = Coll::user_create($data);
            return myok('财务信息已登记');
        } else {
            //修改企业信息
            $sb = Coll::user_reinfo($data);
            return myok('财务信息修改成功');
        }
    }

    
    /**
     * 判断账号是否登录
     * @return boolean [description]
     */
    private function is_login()
    {
        $data = UserModel::is_sessionlogin();
        if (!$data['code']) {
            $data['options'] = 'relogin';
            json($data)->send();
            exit;
        }
    }
}
